package com.epfresh.supplier.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.utils.CashierInputFilter;
import com.epfresh.api.utils.FormatUtil;
import com.epfresh.api.utils.T;
import com.epfresh.supplier.R;
import com.epfresh.supplier.entity.JoinStoreListBean;

import java.math.BigDecimal;

import multitype.ItemViewBinder;
import multitype.OnRecyclerViewItemClickListener;


public class JoinPriceGoodsListViewBinder extends ItemViewBinder<JoinStoreListBean.ProductInfoBean, JoinPriceGoodsListViewBinder.ViewHolder> implements View.OnClickListener {

    OnRecyclerViewItemClickListener onRecyclerViewItemClickListener;
    OnUpdateListener onUpdateListener;
    OnGroupListener onGroupListener;
    OnTextChangerListener onTextChangerListener;

    public OnTextChangerListener getOnTextChangerListener() {
        return onTextChangerListener;
    }

    public void setOnTextChangerListener(OnTextChangerListener onTextChangerListener) {
        this.onTextChangerListener = onTextChangerListener;
    }

    public OnGroupListener getOnGroupListener() {
        return onGroupListener;
    }

    public void setOnGroupListener(OnGroupListener onGroupListener) {
        this.onGroupListener = onGroupListener;
    }

    public OnUpdateListener getOnUpdateListener() {
        return onUpdateListener;
    }

    public void setOnUpdateListener(OnUpdateListener onUpdateListener) {
        this.onUpdateListener = onUpdateListener;
    }

    public OnRecyclerViewItemClickListener getOnRecyclerViewItemClickListener() {
        return onRecyclerViewItemClickListener;
    }

    public void setOnRecyclerViewItemClickListener(OnRecyclerViewItemClickListener onRecyclerViewItemClickListener) {
        this.onRecyclerViewItemClickListener = onRecyclerViewItemClickListener;
    }

    //更新某个位置的数据
    public void notifyItem(int position) {
        if (position > -1 && position < getAdapter().getItemCount())
            getAdapter().notifyItemChanged(position);
    }

    @NonNull
    @Override
    protected ViewHolder onCreateViewHolder(
            @NonNull LayoutInflater inflater, @NonNull ViewGroup parent) {
        View view = inflater.inflate(R.layout.item_join_goods_child, parent, false);
        return new ViewHolder(view);
    }


    @Override
    protected void onBindViewHolder(@NonNull final ViewHolder holder, @NonNull JoinStoreListBean.ProductInfoBean post) {
        final ViewGroup.LayoutParams layoutParams = holder.ll_content.getLayoutParams();

        if (post.isShow()) {
            if (post.isHeader()) {
                holder.ll_content.setVisibility(View.VISIBLE);
                layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                holder.ll_store.setVisibility(View.VISIBLE);
                holder.rl_goods.setVisibility(View.VISIBLE);
                holder.iv_flag.setImageResource(R.mipmap.join_up);
                Log.e("header", "visible");
            } else {
                holder.ll_content.setVisibility(View.VISIBLE);
                layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                holder.ll_store.setVisibility(View.GONE);
                holder.rl_goods.setVisibility(View.VISIBLE);
                Log.e("no_header", "visible");
            }
            if (post.isFooter()) {
                holder.v_footer.setVisibility(View.VISIBLE);
            } else {
                holder.v_footer.setVisibility(View.GONE);
            }
        } else {
            if (post.isHeader()) {
                holder.iv_flag.setImageResource(R.mipmap.join_down);
                holder.ll_content.setVisibility(View.VISIBLE);
                layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                holder.ll_store.setVisibility(View.VISIBLE);
                holder.rl_goods.setVisibility(View.GONE);
                holder.v_footer.setVisibility(View.VISIBLE);
                Log.e("header", "gone");
            } else {
                holder.ll_content.setVisibility(View.GONE);
                layoutParams.height = 0;
                layoutParams.width = 0;
                holder.ll_store.setVisibility(View.GONE);
                holder.rl_goods.setVisibility(View.GONE);
                Log.e("no_header", "gone");
                return;
            }
        }


//        if(post.isUpdatePriceAuth()){
//            holder.tv_price_no_auth.setVisibility(View.GONE);
//            holder.etPrice.setVisibility(View.VISIBLE);
//        }else {
//            holder.tv_price_no_auth.setVisibility(View.VISIBLE);
//            holder.etPrice.setVisibility(View.INVISIBLE);
//        }


        int position = getPosition(holder);
        holder.iv_flag.setTag(R.id.item_key_position, position);
        holder.iv_flag.setTag(R.id.item_key_status, post);
        holder.iv_flag.setOnClickListener(this);
        holder.ll_store.setTag(R.id.item_key_position, position);
        holder.ll_store.setTag(R.id.item_key_status, post);
        holder.ll_store.setOnClickListener(this);
        holder.tvGroup.setTag(R.id.item_key_position, position);
        holder.tvGroup.setTag(R.id.item_key_status, post);
        holder.tvGroup.setOnClickListener(this);

        holder.ivMinus.setTag(R.id.item_key_position, position);
        holder.ivMinus.setTag(R.id.item_key_status, post);
        holder.ivMinus.setOnClickListener(this);
        holder.ivAdd.setTag(R.id.item_key_position, position);
        holder.ivAdd.setTag(R.id.item_key_status, post);
        holder.ivAdd.setOnClickListener(this);

        holder.etPrice.setTag(position);

        holder.etPrice.setTag(R.id.item_key_position, position);
        holder.etPrice.setTag(R.id.item_key_status, post);
        holder.etPrice.addTextChangedListener(new AttTextWatcher(holder));
        holder.etPrice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isKeyboardShow) {
                    hideSoftKeyboard(lastEditText);
                } else {
                    showSoftKeyboard(holder.etPrice);
                    lastEditText = holder.etPrice;
                    lastPost = holder.getAdapterPosition();
                }
            }
        });

        holder.setData(post);
    }

    /**
     * 手动显示软键盘
     *
     * @param view
     */
    public static void showSoftKeyboard(View view) {
        Context context = view.getContext();
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
        if (imm != null) {
            imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
        }
    }

    /**
     * 手动隐藏软键盘
     *
     * @param view
     */
    public static void hideSoftKeyboard(View view) {
        Context context = view.getContext();
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    @Override
    public void onClick(View v) {

        Object tag = v.getTag(R.id.item_key_position);
        if (tag != null && tag instanceof Integer) {
            int position = (int) tag;
            Object o = v.getTag(R.id.item_key_status);
            if (!(o instanceof JoinStoreListBean.ProductInfoBean))
                return;
            if (v.getId() == R.id.iv_flag || v.getId() == R.id.ll_store) {
                JoinStoreListBean.ProductInfoBean bean = (JoinStoreListBean.ProductInfoBean) o;
                if (!bean.isHeader())
                    return;
                boolean show = bean.isShow();
                bean.setShow(!show);
                for (int i = position; i < getAdapter().getItemCount(); i++) {
                    if (getAdapter().getItems().get(i) instanceof JoinStoreListBean.ProductInfoBean) {
                        JoinStoreListBean.ProductInfoBean now = (JoinStoreListBean.ProductInfoBean) getAdapter().getItems().get(i);
                        if (bean.getStoreId().equals(now.getStoreId()))
                            now.setShow(!show);
                        else
                            break;
                    } else {
                        break;
                    }
                }
                getAdapter().notifyDataSetChanged();
            } else if (onRecyclerViewItemClickListener != null && o instanceof JoinStoreListBean.ProductInfoBean) {
                onRecyclerViewItemClickListener.onItemClick(v, position, o);
            }
        }
    }

    private boolean isKeyboardShow = false;
    private EditText lastEditText;
    private int lastPost;

    public void setKeyboardShow(boolean isKeyboardShow) {
        this.isKeyboardShow = isKeyboardShow;
        if (lastEditText != null && !isKeyboardShow) {
            lastEditText.setFocusable(false);
            lastEditText.setFocusableInTouchMode(false);
            if (lastEditText.getText().toString().equals("") ||
                    lastEditText.getText().toString().equals("0") ||
                    lastEditText.getText().toString().equals("0.") ||
                    lastEditText.getText().toString().equals("0.0") ||
                    lastEditText.getText().toString().equals("0.00")) {
                JoinStoreListBean.ProductInfoBean store = (JoinStoreListBean.ProductInfoBean) lastEditText.getTag(R.id.item_key_status);
                BigDecimal unit = getUnit(store);
                store.setPriceNow(unit.doubleValue());
                notifyItem(lastPost);
                T.toast("价格不能小于0");
            }
        }
    }

    private BigDecimal getUnit(JoinStoreListBean.ProductInfoBean goods) {
        BigDecimal unit;
        if (goods.getPrice() * 10 % 1 > 0) {
            unit = new BigDecimal(0.01);
        } else if (goods.getPrice() * 10 % 10 > 0) {
            unit = new BigDecimal(0.1);
        } else {
            unit = new BigDecimal(1);
        }
        return unit;
    }


    private class AttTextWatcher implements TextWatcher {

        ViewHolder holder = null;

        public AttTextWatcher(ViewHolder holder) {
            this.holder = holder;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            JoinStoreListBean.ProductInfoBean store = (JoinStoreListBean.ProductInfoBean) holder.etPrice.getTag(R.id.item_key_status);

            if (TextUtils.isEmpty(s.toString())) {
                store.setPriceNow(0.0);
                return;
            }
            try {
                Double.parseDouble(s.toString());//损失
            } catch (Exception ex) {
                store.setPriceNow(0.0);
                return;
            }
            store.setPriceNow(new BigDecimal(Double.parseDouble(s.toString())).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            if (store.getPriceNow() > 99999.99) {
                store.setPriceNow(99999.99);
                T.toast("价格不能大于99999.99");
                getAdapter().notifyItemChanged(getPosition(holder));
            }

            if (store.getPrice() != store.getPriceNow()) {
                holder.etPrice.setTextColor(Color.RED);
            } else {
                holder.etPrice.setTextColor(0xff434343);
            }

            if (onTextChangerListener != null)
                onTextChangerListener.onChange();


        }

    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        View ll_content, rl_goods, ll_store, v_footer;
        ImageView iv_flag;
        TextView tv_price_no_auth;
        TextView tv_store_title;


        ImageView iv;
        ImageView ivAdd;
        ImageView ivMinus;
        TextView tvTitle;
        TextView tvPackage;
        EditText etPrice;
        TextView tvInventory;
        TextView tvUnit;
        TextView tvGroup;
        TextView tv_sale_price_title;
        View vUpdateBg;
        private TextView tv_validity;


        ViewHolder(@NonNull View itemView) {
            super(itemView);
            ll_content = itemView.findViewById(R.id.ll_content);
            rl_goods = itemView.findViewById(R.id.rl_goods);
            ll_store = itemView.findViewById(R.id.ll_store);
            v_footer = itemView.findViewById(R.id.v_footer);
            iv_flag = itemView.findViewById(R.id.iv_flag);
            tv_store_title = itemView.findViewById(R.id.tv_store_title);
            tv_price_no_auth = itemView.findViewById(R.id.tv_price_no_auth);

            iv = (ImageView) itemView.findViewById(R.id.iv_info_img);
            ivAdd = (ImageView) itemView.findViewById(R.id.iv_add);
            ivMinus = (ImageView) itemView.findViewById(R.id.iv_minus);
            tv_sale_price_title = (TextView) itemView.findViewById(R.id.tv_sale_price_title);
            tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
            tvPackage = (TextView) itemView.findViewById(R.id.tv_package);
            tvInventory = (TextView) itemView.findViewById(R.id.tv_inventory);
            tvGroup = (TextView) itemView.findViewById(R.id.tv_group);
            tvUnit = (TextView) itemView.findViewById(R.id.tv_unit);
            vUpdateBg = itemView.findViewById(R.id.v_update);
            etPrice = (EditText) itemView.findViewById(R.id.et_price);
            etPrice.setFilters(new InputFilter[]{new CashierInputFilter()});
            //有效期
            tv_validity = (TextView) itemView.findViewById(R.id.tv_validity);


        }

        @SuppressLint("SetTextI18n")
        void setData(JoinStoreListBean.ProductInfoBean productInfoBean) {
//            JoinStoreListBean.ProductInfoBean post = store.getProductInfo();
            String thumbnail = productInfoBean.getThumbnail();
            ImageLoader.getInstance().displayImage(thumbnail, iv);
            if (productInfoBean.isJointEnabled()) {
                tvTitle.setText(Html.fromHtml("<font color=\"#00ff7900\">[联营]</font>" + productInfoBean.getTitle()));
            } else {
                tvTitle.setText(productInfoBean.getTitle());
            }

            if (null != productInfoBean.getOriginalPrice()) {
                if (productInfoBean.getOriginalPrice() == 0) {
                    tv_validity.setText("尚未报价");
                } else {
                    if (productInfoBean.isJointEnabled()) {
                        tv_validity.setText("价格长期有效");
                    } else {
                        if (productInfoBean.isFailureTimeStatus()){
                            tv_validity.setText("价格 于" + (TextUtils.isEmpty(productInfoBean.getJointPriceFailureTime()) ? "" : productInfoBean.getJointPriceFailureTime()) + " 失效");
                        }else {
                            tv_validity.setText("价格 " + (TextUtils.isEmpty(productInfoBean.getJointPriceFailureTime()) ? "" : productInfoBean.getJointPriceFailureTime()) + " 前有效");
                        }
                    }
                }

            }
            if (productInfoBean.getSpecName() == null || productInfoBean.getSpecName().equals("默认")) {
                tvPackage.setText(productInfoBean.getPack());
            } else {
                if (null != productInfoBean.getPackageContainer() && productInfoBean.getPackageContainer().equals("散货")) {
                    tvPackage.setText(productInfoBean.getSpecName());
                } else {
                    tvPackage.setText(productInfoBean.getSpecName() + "(" + productInfoBean.getPack() + ")");
                }
            }
            tvUnit.setText("元/" + productInfoBean.getChargeUnit());
            tv_store_title.setText(productInfoBean.getCenterName() + "(" + productInfoBean.getCnt() + ")");

            tv_price_no_auth.setText(FormatUtil.subZeroAndDot(productInfoBean.getPriceOnly()) + "元/" + productInfoBean.getChargeUnit());

            if (productInfoBean.getPrice() == productInfoBean.getPriceNow()) {
                etPrice.setText(FormatUtil.subZeroAndDot(productInfoBean.getPrice()));
                etPrice.setTextColor(Color.parseColor("#434343"));
            } else {
                etPrice.setText(FormatUtil.subZeroAndDot(productInfoBean.getPriceNow()));
                etPrice.setTextColor(Color.RED);
            }
        }
    }


    public interface OnUpdateListener {
        void onUpdate(int position, JoinStoreListBean goods);
    }

    public interface OnGroupListener {
        void onGroup(int position, JoinStoreListBean goods);
    }

    public interface OnTextChangerListener {
        void onChange();
    }


}
